#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This module uses telnet to connect to your D-Link DSL 500G router under a
specified address and port. Once connected, you will be able to send your
commands to the device's CLI and get the response.

written by Arthur Furlan <arthur.furlan@gmail.com>
"""

from dlink import DLink
import re, telnetlib

class DSL500G(DLink):

    def connect(self, username, password):
        self.telnet = telnetlib.Telnet(self.address, self.port)
        self.telnet.read_until('login: ')
        self.telnet.write("%s\n" % username)
        self.telnet.read_until('password: ')
        self.telnet.write("%s\n" % password)
        response = self.telnet.expect(['\$'], 5)
        if response[0] == -1:
            raise Exception('Login failed.')
        self.connected = True

    def command(self, cmd):
        if not self.connected:
            raise Exception('Not connected.')
        self.connected = not (cmd in ['quit', 'reboot'])
        self.telnet.write("%s\n" % cmd)
        if self.connected:
            response = self.telnet.read_until('$').replace('\r', '').split('\n')
            if re.match('^Error: ', response[1]):
                raise Exception(re.sub('^Error: ', '', response[1]))
            return '\n'.join(response[1:len(response)-1])
        else:
            self.__del__()
